<script setup>
import {onMounted, reactive, ref} from "vue";
import {
  createGroup,
  getGroupList,
  getGroupRequestList,
  requestJoinGroup,
  updateGroupRequest
} from "@/apis/chat/group.js";
import {uploadFile} from "@/apis/chat/file.js";
import {userInfoStore} from "@/stores/user.js";
import {ElMessage} from "element-plus";

const user = userInfoStore()
const groupList = ref([]);
const searchResults = ref([]);
const searchInput = ref('');
const joinSearchInput = ref('');
const btn = ref(null);
const popMenu = ref(null)
const visible = ref(false);
const model = ref(null);

const rightIndex = ref('GroupRequest');

const groupRequestList = ref([])

const groupForms = reactive({
  groupName: '',
  groupAvatar: '',
  groupDesc: '群主很懒，什么也没写....',
})

onMounted(() => {
  btn.value.addEventListener('mouseenter', () => {
    popMenu.value.style.display = 'block'
  })
  document.addEventListener('click', () => {
    if (popMenu.value) {
      popMenu.value.style.display = 'none'
    }
  })
})

const fetchGroupList = () => {
  getGroupList({groupOwner: user.userInfo.userId}).then(res => {
    groupList.value = res.data;
  })
}
fetchGroupList();
const fetchGroupRequestList = async () => {
  const resp = await getGroupRequestList({reviewer: user.userInfo.userId})
  groupRequestList.value = resp.data
  return resp.data;
}
fetchGroupRequestList();

const search = async () => {
  const resp = await getGroupList({groupName: searchInput.value})
  if (resp.code === 200) {
    groupList.value = resp.data;
    groupList.value.forEach(item => item.groupName = item.groupName.replace(searchInput.value, `<span style="color: red">${searchInput.value}</span>`))
  }
}

const joinSearch = async () => {
  const resp = await getGroupList({groupOwner: -user.userInfo.userId, groupName: joinSearchInput.value})
  if (resp.code === 200) {
    searchResults.value = resp.data;
    searchResults.value
        .forEach(item => item.groupName = item.groupName
            .replace(joinSearchInput.value, `<span style="color: red">${joinSearchInput.value}</span>`))
  }
}
const clickJoinGroup = async () => {
  console.log('clickJoinGroup')
  model.value = 'joinGroup'
  const resp = await getGroupList({groupOwner: -user.userInfo.userId})
  if (resp.code === 200) {
    searchResults.value = resp.data;
    visible.value = true
  }
}
const clickCreateGroup = () => {
  console.log('clickCreateGroup')
  model.value = 'createGroup'
  visible.value = true
}

const fileChange = (e) => {
  const file = e.target.files[0];
  const formData = new FormData();
  formData.append('file', file);
  ElMessage.info('头像上传中....')
  uploadFile(formData)
      .then(resp => {
        if (resp.code === 200) {
          groupForms.groupAvatar = resp.data;
        }
      })
}

const clickCreate = () => {
  groupForms.groupOwner = user.userInfo.userId
  createGroup(groupForms)
      .then(resp => {
        if (resp.code === 200) {
          visible.value = false;
          fetchGroupList();
        }
      })
}

const joinGroup = (item) => {
  requestJoinGroup({
    groupId: item.id,
    userId : user.userInfo.userId,
    reviewer: item.groupOwner,
    type: 'join'
  }).then(resp => {
    if (resp.code === 200) {
      ElMessage.success('申请已发送')
    }
  })
}

const clickUpdateGroupRequest = (item, status) => {
  item.request.status = status;
  updateGroupRequest({
    ...item.request,
  }).then(resp => {
    if (resp.code === 200) {
      ElMessage.success('操作成功')
      fetchGroupRequestList();
    }
  })
}

</script>

<template>
  <div class="self-container">
    <div class="left-box">
      <div class="search-box">
        <div>
          <el-input
              clearable
              type="text"
              v-model="searchInput"
              @keyup.enter="search"
              @blur="search"
              placeholder="搜索群组"
          />
        </div>
        <div style="position: relative">
          <button ref="btn">+</button>
          <div ref="popMenu" class="pop-menu">
            <div @click="clickJoinGroup">添加群</div>
            <div @click="clickCreateGroup">创建群</div>
          </div>
        </div>
      </div>
      <div class="group-list" >
        <div :key="item.id" v-for="item in groupList" class="group-item">
          <div class="group-item-box">
            <img :src="item.groupAvatar" alt="">
            <div>
              <div v-html="item.groupName"></div>
              <p>{{ item.groupDesc }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-fill">
      <div class="request-panel" v-if="rightIndex === 'GroupRequest'">
        <h2>群聊申请</h2>
        <div class="request-list">
          <div v-for="item in groupRequestList" class="request-item">
            <img :src="item.user.avatar" alt="avatar">
            <div>{{ item.user.username }}</div>
            <div>正在申请加入您的群聊 <strong>{{ item.group.groupName }}</strong> </div>
            <span>{{ item.request.createTime }}</span>

            <div class="btns">
              <el-button type="primary" @click="clickUpdateGroupRequest(item, 'APPROVED')">同意</el-button>
              <el-button type="info" @click="clickUpdateGroupRequest(item, 'REJECTED')">拒绝</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <el-dialog v-model="visible">
    <div v-if="model === 'joinGroup'" class="modal-container">
        <div class="input-box">
          <el-input
              clearable
              type="text"
              v-model="joinSearchInput"
              @keyup.enter="joinSearch"
              @blur="joinSearch"
              placeholder="搜索群组"
          />
        </div>
        <div class="search-result">
          <div v-for="item in searchResults" class="group-item">
            <div class="group-item-box">
              <img :src="item.groupAvatar" alt="">
              <div>
                <div v-html="item.groupName"></div>
                <p>{{ item.groupDesc }}</p>
              </div>

            </div>
            <div class="join-btn">
              <el-button size="small" @click="joinGroup(item)"> 加入群聊 </el-button>
            </div>
          </div>
        </div>
    </div>
    <div v-else-if="model === 'createGroup'" class="modal-container">
      <div style="width: 80%; margin: 0 auto;">
        <div>
          <div style="display: flex; justify-content: center" v-if="groupForms.groupAvatar">
            <img style="width: 4rem; height: 4rem; border-radius: 50%" :src="groupForms.groupAvatar" alt="avatar" >
          </div>
          <div style="display: flex; justify-content: center" v-else>
            <div @click="$refs.fileInput.click()" style="background: #6a6a6a; border-radius: 50%; width: 4rem; height: 4rem;"></div>
            <input
                ref="fileInput"
                hidden
                type="file"
                @change="fileChange"
                accept="image/*"
            />
          </div>
        </div>
        <el-input
            class="mt-2"
            placeholder="群聊名称"
            v-model="groupForms.groupName"
          ></el-input>
        <el-input
            class="mt-2"
            placeholder="群聊描述"
            outlined
            dense
            v-model="groupForms.groupDesc"
        ></el-input>
        <div style="text-align: center">
          <el-button
              type="primary"
              class="mt-2"
              @click="clickCreate"
          >
            创建群聊
          </el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.self-container {
  height: 100%;
  display: flex;
}
.left-box {
  background: #faf7f7;
  width: 22%;
  border-right: 1px solid #e0dcdc;
}

.search-box {
  position: sticky;
  height: 3.5rem;
  top: 0;
  display: flex;
  align-items: center;
  padding: .5em;
}
.search-box > div {
  height: 2em;
}

.search-box button {
  margin-left: 1em;
  width: 2em;
  padding: .5em;
  border: none;
  background-color: #b6b6b6;
}
.mt-2 {
  margin-top: 1rem;
}
.flex-fill {
  flex: 1;
}
.group-list {
  height: 100%;
  overflow-y: auto;
}

.search-result {
  margin-top: 1rem;
}

.group-item{
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 .5em;
}
.group-item:hover {
  background-color: #e0dcdc;
  cursor: pointer;
}
.group-item-box {
  display: flex;
  align-items: center;
  padding: .5em .7em;
  cursor: pointer;

  p {
    font-size: .8em;
    color: #6a6a6a;
    margin-top: .5em;
    max-width: 12rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.group-item-box:hover {
  background-color: #e0dcdc;
}
.group-item-box img {
  width: 3em;
  height: 3em;
  border-radius: 50%;
  margin-right: .5em;
}
.pop-menu {
  display: none;
  background: white;
  position: absolute;
  width: 6rem;
  border-radius: .5em;
  box-shadow: #cecdcd 0 0 10px ;
}
.pop-menu div {
  padding: .5em;
  text-align: center;
  cursor: pointer;
}
.pop-menu div:hover {
  background-color: #e0dcdc;
  border-radius: .5em;
}
.modal-container {
  min-height: 500px;
  padding: 1em;
  background: white;
}

.input-box input {
  width: 100%;
  height: 100%;
  padding: .5em 1em;
  outline: none;
  background-color: #cccccc;
}
.request-panel {
  padding: 1em;
}
.request-item {
  padding: 1em .5em;
  margin-top: 1em;
  background: white;
  border-radius: .5em;
}
.request-item:after {
  content: '';
  display: block;
  clear: both;
  height: 0;
  overflow: hidden;
  visibility: hidden;
  width: 0;
}
.request-item img {
  float: left;
  width: 2rem;
  height: 2rem;
  border-radius: 50%;
  margin-right: .5em;
}
.request-item div {
  margin-left: .2em;
  float: left;
}
.request-item span {
  margin-left: 1em;
  color: #6a6a6a;
  float: left;
}
.request-item .btns {
  float: right;
}
</style>

